This is a custom extension for the python markdown library that allows support for MathJax, which means if you type in a math block in markdown (Typora), it will automatically export correctly to MathJax compatible format when using the python markdown library.
import re
import os
import markdown as md
class MathJaxExtension(md.Extension):
def extendMarkdown(self, md):
""" Add FencedBlockPreprocessor to the Markdown instance. """
md.registerExtension(self)
md.preprocessors.register(MathJaxPreprocessor(md), 'mathjax', 25)
class MathJaxPreprocessor(md.preprocessors.Preprocessor):
MATHJAX_RE = re.compile(r'(?<!\\)(\$\$?)(.+?)\2')#,re.MULTILINE | re.DOTALL | re.VERBOSE)
CODE_WRAP = '<math>%s</math>'
LANG_TAG = ' class="%s"'
def run(self,lines):
text = "\n".join(lines)
while 1:
m = self.MATHJAX_RE.search(text)
if m:
text = '%s\n%s\n%s' % (text[:m.start()],
'',
text[m.end():])
else:
break
return text.split("\n")
def makeExtension(**kwargs): # pragma: no cover
return MathJaxExtension(**kwargs)
How to use the extension to translate a markdown file with a math block to HTML:
### EXAMPLE OF USING THE EXTENSION ###
fn = "example.md"
with open(fn, 'r') as f:
# md.markdown takes custom md.Extension class in "extensions="
html = md.markdown(f.read(), extensions=[MathJaxExtension()])